package com.assetmanage.controller;

import com.assetmanage.model.Borrow;
import com.assetmanage.service.BorrowService;
import com.assetmanage.service.impl.BorrowServiceImpl;
import com.assetmanage.utils.Result;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Calendar;

@WebServlet(urlPatterns = {"/api/borrows/*", "/api/borrows"})
public class BorrowServlet extends BaseServlet {
    private BorrowService borrowService = new BorrowServiceImpl();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

    // 获取所有借用记录
    public void getAllBorrows(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writeSuccess(resp, borrowService.getAllBorrows());
    }

    // 根据用户ID获取借用记录
    public void getBorrowsByUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uIdStr = req.getParameter("uid");
        if (uIdStr == null) {
            writeError(resp, "用户ID不能为空");
            return;
        }

        try {
            int uid = Integer.parseInt(uIdStr);
            writeSuccess(resp, borrowService.getBorrowsByUser(uid));
        } catch (NumberFormatException e) {
            writeError(resp, "用户ID必须是数字");
        }
    }

    // 根据资产ID获取借用记录
    public void getBorrowsByAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String assetId = req.getParameter("assetId");
        if (assetId == null) {
            writeError(resp, "资产ID不能为空");
            return;
        }
        writeSuccess(resp, borrowService.getBorrowsByAsset(assetId));
    }

    // 添加借用记录
    public void addBorrow(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String requestBody = sb.toString();
            System.out.println("收到的借用请求数据: " + requestBody);
            
            // 使用GSON直接解析JSON，它会自动处理日期格式
            Borrow borrow = gson.fromJson(requestBody, Borrow.class);
            
            // 如果前端没有传入borrowTime，设置为当前时间
            if (borrow.getBorrowTime() == null) {
                borrow.setBorrowTime(new Date());
            }
            
            // 如果前端没有传入expectedReturnTime，默认设置为借用时间
            if (borrow.getExpectedReturnTime() == null) {
                borrow.setExpectedReturnTime(borrow.getBorrowTime());
            }
            
            // 打印详细的借用信息用于调试
            System.out.println("解析后的借用对象: " +
                "\n  uId=" + borrow.getUId() +
                "\n  assetId=" + borrow.getAssetId() +
                "\n  borrowNum=" + borrow.getBorrowNum() +
                "\n  borrowStatus=" + borrow.getBorrowStatus() +
                "\n  borrowTime=" + dateFormat.format(borrow.getBorrowTime()) +
                "\n  expectedReturnTime=" + dateFormat.format(borrow.getExpectedReturnTime()) +
                "\n  borrowReason=" + borrow.getBorrowReason());
            
            if (borrowService.addBorrow(borrow)) {
                System.out.println("借用记录添加成功");
                writeSuccess(resp, null);
            } else {
                System.out.println("借用记录添加失败");
                writeError(resp, "添加借用记录失败");
            }
        } catch (Exception e) {
            System.err.println("添加借用记录时发生异常: " + e.getMessage());
            e.printStackTrace();
            writeError(resp, "添加借用记录失败: " + e.getMessage());
        }
    }

    // 更新借用状态
    public void updateBorrowStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String requestBody = sb.toString();
            System.out.println("收到的借用状态更新请求数据: " + requestBody);
            
            // 从URL路径中获取borrowId
            String pathInfo = req.getPathInfo();
            System.out.println("请求路径: " + pathInfo);
            
            if (pathInfo == null || pathInfo.length() <= 1) {
                writeError(resp, "借用ID不能为空");
                return;
            }
            
            // 提取borrowId，去掉开头的斜杠，并且只取问号之前的部分
            String borrowIdStr = pathInfo.substring(1);
            int questionMarkIndex = borrowIdStr.indexOf('?');
            if (questionMarkIndex > 0) {
                borrowIdStr = borrowIdStr.substring(0, questionMarkIndex);
            }
            System.out.println("从路径中提取的borrowId: " + borrowIdStr);
            
            try {
                int borrowId = Integer.parseInt(borrowIdStr);
                System.out.println("解析到的borrowId: " + borrowId);
                
                // 解析请求体中的状态
                if (requestBody == null || requestBody.isEmpty()) {
                    writeError(resp, "请求数据不能为空");
                    return;
                }
                
                JsonObject jsonObject = gson.fromJson(requestBody, JsonObject.class);
                if (jsonObject == null || !jsonObject.has("borrowStatus")) {
                    writeError(resp, "借用状态不能为空");
                    return;
                }
                
                String newStatus = jsonObject.get("borrowStatus").getAsString();
                if (newStatus == null || newStatus.isEmpty()) {
                    writeError(resp, "借用状态不能为空");
                    return;
                }
                
                System.out.println("更新借用状态: borrowId=" + borrowId + ", newStatus=" + newStatus);
                
                // 更新状态
                if (borrowService.updateBorrowStatus(borrowId, newStatus)) {
                    writeSuccess(resp, null);
                } else {
                    writeError(resp, "更新借用状态失败");
                }
            } catch (NumberFormatException e) {
                System.err.println("borrowId解析失败: " + borrowIdStr);
                writeError(resp, "借用记录ID必须是数字");
            } catch (Exception e) {
                System.err.println("处理请求时发生异常: " + e.getMessage());
                e.printStackTrace();
                writeError(resp, "处理请求失败: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("更新借用状态时发生异常: " + e.getMessage());
            e.printStackTrace();
            writeError(resp, "更新借用状态失败: " + e.getMessage());
        }
    }

    // 删除借用记录
    public void deleteBorrow(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String borrowIdStr = req.getParameter("borrowId");
        System.out.println("收到删除借用记录请求，borrowId参数: " + borrowIdStr);
        
        if (borrowIdStr == null) {
            System.out.println("借用记录ID为空");
            writeError(resp, "借用记录ID不能为空");
            return;
        }

        try {
            int borrowId = Integer.parseInt(borrowIdStr);
            System.out.println("尝试删除借用记录，ID: " + borrowId);
            
            // 先检查记录是否存在
            Borrow borrow = borrowService.getBorrowById(borrowId);
            if (borrow == null) {
                System.out.println("借用记录不存在，ID: " + borrowId);
                writeError(resp, "借用记录不存在");
                return;
            }
            
            if (borrowService.deleteBorrow(borrowId)) {
                System.out.println("借用记录删除成功，ID: " + borrowId);
                writeSuccess(resp, null);
            } else {
                System.out.println("借用记录删除失败，ID: " + borrowId);
                writeError(resp, "删除借用记录失败");
            }
        } catch (NumberFormatException e) {
            System.out.println("借用记录ID格式错误: " + borrowIdStr);
            writeError(resp, "借用记录ID必须是数字");
        }
    }

    // 借用资产
    public void borrowAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uIdStr = req.getParameter("uId");
        String assetId = req.getParameter("assetId");
        String numStr = req.getParameter("num");

        if (uIdStr == null || assetId == null || numStr == null) {
            writeError(resp, "用户ID、资产ID和借用数量不能为空");
            return;
        }

        try {
            int uId = Integer.parseInt(uIdStr);
            int num = Integer.parseInt(numStr);
            if (borrowService.borrowAsset(uId, assetId, num)) {
                writeSuccess(resp, null);
            } else {
                writeError(resp, "借用资产失败，可能是库存不足");
            }
        } catch (NumberFormatException e) {
            writeError(resp, "用户ID和借用数量必须是数字");
        }

    }

    // 归还资产
    public void returnAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String borrowIdStr = req.getParameter("borrowId");
        if (borrowIdStr == null) {
            writeError(resp, "借用记录ID不能为空");
            return;
        }

        try {
            int borrowId = Integer.parseInt(borrowIdStr);
            if (borrowService.returnAsset(borrowId)) {
                writeSuccess(resp, null);
            } else {
                writeError(resp, "归还资产失败，可能是记录不存在或已归还");
            }
        } catch (NumberFormatException e) {
            writeError(resp, "借用记录ID必须是数字");
        }
    }

    // 获取借用记录详情
    public void getBorrowById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String borrowIdStr = req.getParameter("borrowId");
        if (borrowIdStr == null) {
            writeError(resp, "借用记录ID不能为空");
            return;
        }

        try {
            int borrowId = Integer.parseInt(borrowIdStr);
            Borrow borrow = borrowService.getBorrowById(borrowId);
            if (borrow != null) {
                writeSuccess(resp, borrow);
            } else {
                writeError(resp, "借用记录不存在");
            }
        } catch (NumberFormatException e) {
            writeError(resp, "借用记录ID必须是数字");
        }
    }

    // 获取使用统计数据
    public void getUsageStats(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String month = req.getParameter("month");  // 格式：YYYY-MM
        String depId = req.getParameter("depId");  // 部门ID，"all"表示所有部门
        
        if (month == null || month.isEmpty()) {
            writeError(resp, "月份参数不能为空");
            return;
        }
        
        try {
            // 解析月份参数，获取该月的起始日期和结束日期
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startDate = monthFormat.parse(month);
            
            // 获取月末日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.set(Calendar.DAY_OF_MONTH, 1);  // 设置为月初
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            startDate = calendar.getTime();

            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));  // 设置为月末
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date endDate = calendar.getTime();
            
            // 打印日期范围用于调试
            System.out.println("查询日期范围: " + fullFormat.format(startDate) + " 到 " + fullFormat.format(endDate));
            
            // 获取统计数据
            List<Borrow> stats = borrowService.getUsageStats(startDate, endDate, depId);
            writeSuccess(resp, stats);
            
        } catch (ParseException e) {
            writeError(resp, "月份格式错误，应为YYYY-MM");
        } catch (Exception e) {
            writeError(resp, "获取使用统计数据失败: " + e.getMessage());
        }
    }

    // 更新借用记录
    public void updateBorrow(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String requestBody = sb.toString();
            System.out.println("收到的借用记录更新请求数据: " + requestBody);
            
            // 从URL路径中获取borrowId
            String pathInfo = req.getPathInfo();
            if (pathInfo == null || pathInfo.length() <= 1) {
                writeError(resp, "借用ID不能为空");
                return;
            }
            
            // 提取borrowId，去掉开头的斜杠，并且只取问号之前的部分
            String borrowIdStr = pathInfo.substring(1);
            int questionMarkIndex = borrowIdStr.indexOf('?');
            if (questionMarkIndex > 0) {
                borrowIdStr = borrowIdStr.substring(0, questionMarkIndex);
            }
            
            try {
                int borrowId = Integer.parseInt(borrowIdStr);
                
                // 解析请求体
                Borrow borrow = gson.fromJson(requestBody, Borrow.class);
                if (borrow == null) {
                    writeError(resp, "请求数据格式错误");
                    return;
                }
                
                // 设置borrowId
                borrow.setBorrowId(borrowId);
                
                // 更新借用记录
                if (borrowService.updateBorrow(borrow)) {
                    writeSuccess(resp, null);
                } else {
                    writeError(resp, "更新借用记录失败");
                }
            } catch (NumberFormatException e) {
                writeError(resp, "借用记录ID必须是数字");
            }
        } catch (Exception e) {
            System.err.println("更新借用记录时发生异常: " + e.getMessage());
            e.printStackTrace();
            writeError(resp, "更新借用记录失败: " + e.getMessage());
        }
    }
} 